package tx.common;

import cn.stimd.spring.beans.factory.annotation.Autowired;
import cn.stimd.spring.context.stereotype.Repository;
import cn.stimd.spring.jdbc.core.JdbcTemplate;
import cn.stimd.spring.jdbc.core.RowMapper;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * Created by Stimd
 * 项目地址：https://gitee.com/stimd/spring-wheel
 * 公众号：Java编程探微
 */
@Repository
public class UserDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;


    private static final RowMapper<User> ROW_MAPPER = new RowMapper<User>() {
        @Override
        public User mapRow(ResultSet rs, int rowNum) throws SQLException {
            User user = new User();
            user.setId(rs.getInt(1));
            user.setName(rs.getString(2));
            user.setPhone(rs.getString(3));
            return user;
        }
    };


    public List<User> getAll(){
        String sql = "SELECT id, name, phone FROM t_user";
        return this.jdbcTemplate.query(sql, ROW_MAPPER);
    }

    public User getByPhone(String phone){
        String sql = "SELECT id, name, phone FROM t_user WHERE phone = ?";
        return this.jdbcTemplate.queryForObject(sql, ROW_MAPPER, phone);
    }


    public int save(String name, String phone){
        String sql = "INSERT INTO t_user SET name = ?, phone = ?";
        return jdbcTemplate.update(sql, name, phone);
    }
}
